import socket
from utils import coding_type, decode
from bdtime import tt

server_addr = ('', 8888)
# server_addr = ('', 8011)
# client_addr = ('', 8000)


def main():
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.bind(server_addr)
    tcp_server_socket.listen(128)
    print(f'--- server开启, server_addr: {server_addr} ---')

    new_client_socket = None
    tt.__init__()
    try:
        while True:
            new_client_socket, client_addr = tcp_server_socket.accept()
            print(f'--- {tt.now(1)} new_client_socket, client_addr: ({new_client_socket, client_addr})')

            while True:
                try:
                    recv_data_0 = new_client_socket.recv(1024)
                    if recv_data_0 is None:
                        break
                except Exception as e:
                    print('断开连接 -->', e)
                    break

                recv_data = decode(recv_data_0)
                # recv_data = recv_data_0.decode('utf-8')

                if recv_data != '0' and recv_data:
                    new_client_socket.send(f'Enter|--- recv_data: ({recv_data}), server收到数据时间: {tt.now(1)}s'.encode('utf-8'))
                else:
                    print(f'---------- 正在断开({client_addr})的连接...')
                    new_client_socket.close()
                    print('已断开.')
                    break

                print(f"--- {tt.now(1)} 收到数据: {recv_data}")
    except Exception as e:
        try:
            if new_client_socket:
                new_client_socket.close()
        except Exception as e:
            print(e)
        tcp_server_socket.close()
        raise e


if __name__ == '__main__':
    main()
